define([
  'jquery',
  'underscore',
  'models/AlertMessage',
  'views/View',
  'views/Item',
  'views/GenericError'
], function($, _, AlertMessage, View, ItemView, GenericErrorView){
  var ListView = View.extend({
    // Property for rendering the items using this view.
    itemView: ItemView, // TODO,
    listEvents: {},
    initList: function(){},
    
    events: function() {
      return _.extend({
	"click a.page":		"changePage"
      }, this.listEvents);
    },

    initialize: function(options) {
      options || (options = {});
      
      // Call super initialize
      View.prototype.initialize.call(this, options);
      
      this.collection.bind("add", this.render, this);
      this.collection.bind("reset", this.render, this);
//      this.collection.bind("change", this.render, this);
      //this.collection.bind("success_fetch", this.successFetch, this);
      this.collection.bind("error_fetch", this.errorFetch, this);
      
//      this.collection.pagination.setLimit(5);
      this.initList(options); // Call initialization function of the implemented list.
    },
    
    render: function() {
      this.renderList();
      
      return this;
    },
    
    renderList: function(flags) {
      // Build pagination and the body template
      var pagination = this.collection.pagination;
      // TODO temp method for testing!
      $(this.el).html(this.template(this.getRenderData()));
      var self = this;
      
      // Build the list
      var $list = this.$(".list");
      _.each(pagination.models(), function(item){        
	var itemView = new self.itemView({
	  model:	item,
	  collection: self.collection,
          flags: flags || this.flags
	});
	$list.append(itemView.render().el);

        // Trigger event to notify the item view that it was attached to the DOM.
        itemView.trigger("list:append");
      });
    },
    
    changePage: function(e) {
      this.Logger.debug("Change page");
      e.preventDefault();
      var page = $(e.currentTarget).data("id") ? $(e.currentTarget).data("id") : 1;
      this.collection.pagination.setPage(page);
    },

    successFetch: function() {
      this.Logger.debug("SuccessFETCH");
      var message = new AlertMessage({title: "La coleccion se ha cargado correctamente."});
      this.addMessage(message);
    },
    
    errorFetch: function() {
      var modal = new GenericErrorView();
      modal.render();
    },

    getRenderData: function() {
      var data = {};
      data.pagination = this.collection.pagination.info();
      return data;
    }
  });

  return ListView;
});
